/**
 * xqx,2023.08.11
 * 后台翻译模块
 * 模块translate是layui扩展模块
 */
layui.define(['translate'], function(exports) {
    var translate = layui.translate;
    translate.selectLanguageTag.show = false; //不出现的select的选择语言
    translate.language.setLocal('chinese_simplified');

    var adminTranslate = {
        execute: function(isfirst){
            xy_translate_page(isfirst);
        },
        //直接将英语翻译成目标语言，主要用于提示信息的翻译
        trans_info: function(text){
            var to = sessionStorage.getItem("toLang");  //目标语言
            var search = adminlangsDict[to][adminlangsDict['en'].indexOf(text)];
            if(search && search.trim() !=''){
                return search;
            }else{
                return text;
            }
        },
        trans_table: function(){
            if(sessionStorage.getItem("fromLang") == sessionStorage.getItem("toLang")){
                return;
            }
            parsePage();
            select(1,1);
        }
    };

    /** 进行文字替换形式翻译页面 start */
    /**
     * 2023.08.11  xqx
     * 翻译页面
     * @isfirst  1:首次进入页面；0:切换语言时
     */
    function xy_translate_page(isfirst = 1){
        console.log('lang: ',sessionStorage.getItem("fromLang") ,' => ', sessionStorage.getItem("toLang"));
        if(sessionStorage.getItem("fromLang") == sessionStorage.getItem("toLang")){
            return;
        }
        var text = '';
        // 标题
        $('title').text(xy_translate_word($('title')));
        //页面上方head部分
        $('.tpl-header-navbar li a:first-child').each(function(){
            let t = $(this).text().trim();
            if(t.indexOf('，')!=-1){
                $(this).html($(this).html().replace(t.split('，')[0],xy_translate_word(t.split('，')[0]))); 
            }else{
                $(this).html(xy_translate_word($(this)));
            }
        });

        //左侧导航一级菜单 标题
        $('.sidebar-nav-heading').html(xy_translate_word($('.sidebar-nav-heading')));
        //页面左侧导航子级菜单 标题
        $('.sidebar-second-title').text(xy_translate_word($('.sidebar-second-title')));
        //菜单
        $('.left-sidebar a').each(function(i,n){
            $(this).html(xy_translate_word($(this)));
        });

        //内容标题
        $('.widget-title').html(xy_translate_word($('.widget-title')));

        //按钮
        xy_trans_elems(['.layui-btn']);
        // $('.layui-btn').each(function(){
        //     $(this).html(xy_translate_word($(this)));
        // });

        select(isfirst);
        
        //layui自动翻译组件
        var langArr = {
            'zh' : 'chinese_simplified',
            'en' : 'english',
            'spa' : 'spanish',
            'de' : 'german',
            'ara' : 'arabic'
        };
        // translate.changeLanguage(langArr[sessionStorage.getItem("toLang")]);

    }

    /**
     * xqx 2023.08.15
     * 选择哪个模块进行翻译  
     * @param {*} isfirst 是否首次进行翻译
     * @param {*} istable 是否针对layui表格翻译
     */
    function select(isfirst = 1, istable = 0){
        var moudle = location.pathname.split('/')[1];
        switch (moudle.toLowerCase()) {
            case 'system':
                trans_system(isfirst, istable);
                break;
            case 'permission':
                trans_permission(isfirst, istable);
                break;
            case 'page':
                trans_page(isfirst, istable);
                break;
            case 'lang':
                trans_lang(isfirst, istable);
                break;
            case 'service':
                trans_service(isfirst, istable);
                break;
            case 'order':
                trans_order(isfirst, istable);
                break;
            case 'admin':
                trans_admin(isfirst, istable);
                break;
            case 'goods':
                trans_goods(isfirst, istable);
                break;
            case 'user':
                trans_user(isfirst, istable);
                break;
            default:
                break;
        }
    }

    /**
     * xqx  2023.08.15
     * 翻译订单模块
     * @param {*} isfirst 
     * @param {*} istable 
     * @returns 
     */
    function trans_order(isfirst = 1, istable = 0){
        if(!istable){
            xy_trans_elems(['.layui-btn-group a','select[name=searchtype] option','dd']);
            $('input[readonly]').val(xy_translate_word($('input[readonly]').val()));
            // edit.html
            xy_trans_elems(['.layui-layer-title', 'legend','.agency-param b:first-child', '.layui-tab-title li', '.layui-form-label']);
            $('.agency-country').each(function(i,n){
                let t = $(this).text().split(':')[0];
                $(this).html($(this).html().replace(t,xy_translate_word(t)) );
            });
            $('#totoal-price').each(function(i,n){
                let t = $(this).text().split(':')[0];
                $(this).html($(this).html().replace(t,xy_translate_word(t)) );
            });
        }
        // 翻译layui表格（同个页面不是首次时，对页面进行翻译）
        if(istable || !isfirst){
            xy_trans_table_common();
            xy_trans_elems(['.xy-status','dd','.layui-layer-title']);
            $('input[readonly]').val(xy_translate_word($('input[readonly]').val()));
            //翻译操作记录
            $('td[data-field="log"]').each(function(i,n){
                let html = $(this).html();
                $(this).text().split(';').forEach((elem)=>{
                    let t = elem.split('：')[0];
                    html = html.replace(t,xy_translate_word(t));
                    if(elem.split('：')[1].includes('=>')){
                        elem.split('：')[1].split('=>').forEach((e)=>{
                            html = html.replace(e,xy_translate_word(e));
                        });
                    }
                });
                $(this).html(html);
            });
        }
        
    }

    function trans_system(isfirst = 1, istable = 0){
        console.log('system.....')
        // 系统环境
        xy_trans_elems(['h2','th']);
    }

    function trans_permission(isfirst = 1, istable = 0){
        console.log('permission.....')
    }

    function trans_page(isfirst = 1, istable = 0){
        console.log('trans_page.....')
    }

    function trans_lang(isfirst = 1, istable = 0){
        console.log('trans_lang.....')
        if(!istable){
            xy_trans_elems(['.layui-btn-group a','select[name=searchtype] option','dd']);
            $('input[readonly]').val(xy_translate_word($('input[readonly]').val()));
        }
        if(istable || !isfirst){
            xy_trans_table_common();
            xy_trans_elems(['.xy-status']);
        }
    }

    function trans_service(isfirst = 1, istable = 0){
        console.log('trans_service.....')
    }

    

    function trans_admin(isfirst = 1, istable = 0){
        console.log('trans_admin.....')
        // avatar.html / address.html / repwd.html / selfinfo.html
        xy_trans_elems(['.layui-form-label','#up-modal-frame label','button','#up-modal-loading .am-modal-hd','#up-modal-alert .am-modal-bd','#up-modal-alert .am-modal-btn']);
    }

    function trans_goods(isfirst = 1, istable = 0){
        console.log('trans_goods.....')
    }

    function trans_user(isfirst = 1, istable = 0){
        console.log('user.....')
    }

    function xy_trans_table_common(){
        $('.layui-laypage-limits option').each(function(i,n){
            let t = $(this).text().split(' ')[1].split('/');
            $(this).html($(this).html().replace(t[0],xy_translate_word(t[0])));
            $(this).html($(this).html().replace(t[1],xy_translate_word(t[1])));
        });
        
        xy_trans_elems(['th','.action-btn a','ppp','.layui-laypage-btn','.layui-none']);
    }


    function parsePage(){
        let h = $('.layui-laypage-skip').html();
        if(h){
            h = h.replace('到第','<ppp>'+'到第'+'</ppp>')
            h = h.replace('页','<ppp>'+'页'+'</ppp>');
            $('.layui-laypage-skip').html(h)
        }
        h = $('.layui-laypage-count').html();
        if(h){
            h = h.replace('共','<ppp>'+'共'+'</ppp>')
            h = h.replace('条','<ppp>'+'条'+'</ppp>');
            $('.layui-laypage-count').html(h)
        }
        
        
    }

    function xy_trans_elems(elems){
        elems.forEach(elem => {
            $(elem).each(function(i,n){
                $(this).html(xy_translate_word($(this)));
            });
        });
        
    }

    /**
     * 翻译  2023.07.17  xuqixiang
     * @param {*} elem 文本或文本所在的元素
     * @returns 返回翻译结果
     */
    function xy_translate_word(elem){
        if(!elem){
            return '';
        }
        var from = sessionStorage.getItem("fromLang"),  //原来语言
            to = sessionStorage.getItem("toLang");  //目标语言
        if(typeof(elem)=='string'){
            return find_text(from, to, elem);
        }else{
            return find_elem(from, to, elem);
        }
    }

    /**
     * 翻译元素内的文本  2023.07.27  xuqixiang
     * @param {*} from 源语言
     * @param {*} to 目标语言
     * @param {*} elem 文本所在的元素
     * @returns html
     */
    function find_elem(from, to, elem){
        var text = handleStr(elem.text()).trim();
        if(text != ''){
            var search = adminlangsDict[to][adminlangsDict[from].indexOf(text)];
            if(search && search.trim() !=''){
                return elem.html().replace(text, search);
            }else{
                return elem.html();
            }
        }else{
            return elem.html();
        }
        
    }

    /**
     * 翻译文本  2023.07.27  xuqixiang
     * @param {*} from 源语言
     * @param {*} to 目标语言
     * @param {*} text 文本
     * @returns 翻译后的文本
     */
    function find_text(from, to, text){
        var temp = handleStr(text).trim();
        if(temp != ''){
            var search = adminlangsDict[to][adminlangsDict[from].indexOf(temp)];
            if(search && search.trim() !=''){
                return text.replace(temp, search);
            }else{
                return text;
            }
        }else{
            return text;
        }
        
    }

    // 去除标点符号
    function handleStr(str) {
        return str.replace(/[\?.:：]/g, '');
      }
      
    exports('adminTranslate', adminTranslate); //对外接口
});